package com.wayz.service;

import com.wayz.entity.dto.role.RoleDto;
import com.wayz.entity.dto.role.RoleMenuIdsDto;
import com.wayz.entity.dto.user.UserAdminDto;
import com.wayz.exception.WayzException;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: InitServiceImpl
 * @description: 初始化数据服务
 * <功能详细描述>
 * @author: 须尽欢_____
 * @date: 2019/7/1
 */
@Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class InitServiceImpl implements InitService{

    @Autowired
    private RoleAdminService roleAdminService;

    @Autowired
    private UserAdminService userService;

    @Autowired
    private MenuAdminService menuAdminService;

    @Override
    public String init() throws WayzException {
        Long roleId = this.createRole();
        this.createUser(roleId);
        Integer integer = this.authorityRole(roleId);
        return integer.toString();
    }

    /**
     * 创建角色
     * @throws WayzException
     */
    public Long createRole() throws WayzException {
        RoleDto roleDto = new RoleDto();
        roleDto.setName("平台管理员");
        roleDto.setDescription("管理员");
        Long role = roleAdminService.createRole(1L, roleDto);
        System.out.println("创建角色Id:"+role);
        return role;
    }


    /**
     * 创建用户
     * @throws WayzException
     */
    public Long createUser(Long roleId) throws WayzException {
        UserAdminDto userCreateVo = new UserAdminDto();
        userCreateVo.setUsername("admin");
        userCreateVo.setEmail("saas@wayz.ai");
        userCreateVo.setName("wayz");
        userCreateVo.setPassword("e10adc3949ba59abbe56e057f20f883e");
        userCreateVo.setPhone("13912345678");
        userCreateVo.setRoleId(roleId);
        Long user = userService.createUser(1L, userCreateVo);
        return user;
    }

    /**
     * 角色授权
     */
    public Integer authorityRole(Long roleId){

        RoleMenuIdsDto roleMenuIdsDto = new RoleMenuIdsDto();

        List<Long> myMenus = menuAdminService.menuIdList();
        List<Long> menuList = new ArrayList<>();

        for (Long id : myMenus) {
            menuList.add(id);
        }

        roleMenuIdsDto.setRoleId(roleId);
        roleMenuIdsDto.setMenuIdList(menuList);
        Integer integer = roleAdminService.authorityRole(1L, roleMenuIdsDto);
        return integer;
    }
}
